package com.zyh.homework.test1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author zyh
 * @Date 2024/8/13 19:32
 * @Description
 */

public class Test3 {
    public static void main(String[] args) throws IOException, DocumentException {
        FileReader fileReader = new FileReader("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\homework\\test1\\test.xml");
        List<Book> list = readXml(fileReader);
        for (Book book : list) {
            System.out.println(book);
        }
    }

    public static List<Book> readXml(FileReader reader) throws DocumentException {
        List<Book> list = new ArrayList<>();
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(reader);
        //拿到根节点
        Element rootElement = read.getRootElement();
        //拿到根节点下的子节点
        List<Element> elements = rootElement.elements();
        //遍历子节点
        Iterator<Element> iterator = elements.iterator();
        while (iterator.hasNext()) {
            Element value = iterator.next();
            String title = value.element("title").getText();
            String author = value.element("author").getText();
            String year = value.element("year").getText();
            String price = value.element("price").getText();
            list.add(new Book(title, author, Integer.parseInt(year), Double.parseDouble(price)));
        }
        return list;
    }
}
